/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
#include <vector>
#include <map>
using namespace std;
class Solution {
    map<int, int> m;
    TreeNode *buildTree(vector<int> &inorder, int ih, int it, vector<int> &postorder, int ph, int pt){
        if (ih>it || ph>pt) return NULL;
        TreeNode *ret=new TreeNode(postorder[pt]);
        int index=m[postorder[pt]];
        ret->left=buildTree(inorder, ih, index-1, postorder, ph, ph+index-1-ih);
        ret->right=buildTree(inorder, index+1, it, postorder, ph+index-ih, pt-1);
        return ret;
    }
public:
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
        m.clear();
        int n=inorder.size();
        for (int i=0;i<n;i++) m.insert(make_pair(inorder[i], i));
        return buildTree(inorder, 0, n-1, postorder, 0, n-1);
    }
};
